import React, {Component} from 'react'
import {
    View,
    StyleSheet,
    ScrollView,
    ListView,
    Text,
} from 'react-native'
import TopList from "./TopHeaderList";

let Dimensions = require('Dimensions')
var width = Dimensions.get('window')
export default class TopHeader extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
            dataArr: [],
            activePage: 0
        }
        this.fetchData();
    }

    fetchData() {
        fetch('http://localhost:8081/localdata/topmenu.json')
            .then((response) => response.json())
            .then((responseJson) => {
                this.setState({
                    dataArr: responseJson.data,
                })
            })
            .catch((error) => {
                console.error(error);
            });
    }

    render() {
        return (
            <View>
                <ScrollView
                    style={styles.topScrollview}
                    horizontal={true}
                    pagingEnabled={true}
                    showsHorizontalScrollIndicator={false}
                    onMomentumScrollEnd={this.onScrollAnimationEnd.bind(this)}>
                    {this.renderList()}
                </ScrollView>

                <View style={styles.indicatorContainer}>
                    {this.renderIndicator()}
                </View>
            </View>
        )
    }

    onScrollAnimationEnd(e) {
        //求当前页码
        var currentPage = Math.floor(e.nativeEvent.contentOffset.x / width)
        this.setState({
            activePage: currentPage
        })
    }

    renderList() {
        var itemArr = [];
        var dataArr = this.state.dataArr;
        for (var i = 0; i < dataArr.length; i++) {
            itemArr.push(
                <TopList
                    key={i}
                    itemData={dataArr[i]}
                />
            )
        }
        return itemArr;
    }

    renderIndicator() {
        var indicatorArr = [];
        var style;
        var dataArr = this.state.dataArr;
        for (var i = 0; i < dataArr.length; i++) {
            style = (i === this.state.activePage) ? {backgroundColor: '#f09738'} : {backgroundColor: 'gray'};
            indicatorArr.push(
                <View
                    key={i}
                    sytle={[styles.indicatorView, style]}/>
            );
        }
        return indicatorArr;
    }

}

const styles = StyleSheet.create({

    indicatorView: {
        height: 10,
        width: 10,
        borderRadius: 25,
        backgroundColor: 'red'
    },
    indicatorContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        backgroundColor: '#fff',
        height: 15
    },
    container: {
        flex: 1,
    },
    topScrollview: {
        height: 160,
        backgroundColor: '#fff'
    }

})